<!DOCTYPE html>
<html lang="zh-CN" xmlns:th="http://www.thymeleaf.org" xmlns:sec="http://www.thymeleaf.org/extras/spring-security">
<head th:replace="~{fragments/layout :: head('图书详情')}"></head>
<body>
    <!-- 导航栏 -->
    <nav th:replace="~{fragments/layout :: navbar}"></nav>
    
    <!-- 页面内容 -->
    <div th:replace="~{fragments/layout :: content(~{::main})}">
        <main>
            <div class="row">
                <!-- 图书详情 -->
                <div class="col-md-8">
                    <div class="card mb-4">
                        <div class="card-header bg-primary text-white">
                            <h3 class="card-title mb-0" th:text="${book.title}">图书标题</h3>
                        </div>
                        <div class="card-body">
                            <div class="row mb-3">
                                <div class="col-md-4 fw-bold">作者：</div>
                                <div class="col-md-8" th:text="${book.author}">作者名</div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4 fw-bold">ISBN：</div>
                                <div class="col-md-8" th:text="${book.isbn}">ISBN号</div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4 fw-bold">出版年份：</div>
                                <div class="col-md-8" th:text="${book.publicationYear}">出版年份</div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4 fw-bold">分类：</div>
                                <div class="col-md-8">
                                    <span class="badge bg-secondary" th:text="${book.category}">分类</span>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4 fw-bold">库存状态：</div>
                                <div class="col-md-8">
                                    <span th:if="${book.availableQuantity > 0}" class="badge bg-success">可借阅</span>
                                    <span th:unless="${book.availableQuantity > 0}" class="badge bg-danger">已借完</span>
                                    <span class="ms-2" th:text="'可借: ' + ${book.availableQuantity} + '/' + ${book.quantity}">可借: 0/0</span>
                                </div>
                            </div>
                            <div class="row mb-3">
                                <div class="col-md-4 fw-bold">简介：</div>
                                <div class="col-md-8" th:text="${book.description}">图书简介内容...</div>
                            </div>
                            
                            <!-- 借阅按钮 (仅登录用户可见) -->
                            <div class="mt-4" sec:authorize="isAuthenticated() and !hasRole('ADMIN')">
                                <div th:if="${book.availableQuantity > 0}">
                                    <button th:attr="data-book-id=${book.id}" class="btn btn-primary borrow-btn">
                                        <i class="fas fa-book"></i> 借阅此书
                                    </button>
                                </div>
                                <button th:unless="${book.availableQuantity > 0}" class="btn btn-secondary" disabled>
                                    <i class="fas fa-exclamation-circle"></i> 暂无可借
                                </button>
                            </div>
                            
                            <!-- 借阅请求的JavaScript -->
                            <script th:inline="javascript">
                                document.addEventListener('DOMContentLoaded', function() {
                                    const borrowButtons = document.querySelectorAll('.borrow-btn');
                                    borrowButtons.forEach(button => {
                                        button.addEventListener('click', function() {
                                            const bookId = this.getAttribute('data-book-id');
                                            
                                            // 安全地获取CSRF令牌，如果不存在则使用空字符串
                                            const csrf = /*[[${_csrf}]]*/ null;
                                            const csrfToken = csrf ? csrf.token : '';
                                            const csrfHeader = csrf ? csrf.headerName : 'X-CSRF-TOKEN';
                                            
                                            // 显示借阅中状态
                                            this.disabled = true;
                                            this.innerHTML = '<i class="fas fa-spinner fa-spin"></i> 处理中...';
                                            
                                            // 创建XHR请求
                                            const xhr = new XMLHttpRequest();
                                            xhr.open('POST', `/loans/borrow/${bookId}`, true);
                                            xhr.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded');
                                            
                                            // 只有当CSRF令牌存在时才添加CSRF头
                                            if (csrfToken) {
                                                xhr.setRequestHeader(csrfHeader, csrfToken);
                                            }
                                            
                                            xhr.onload = function() {
                                                if (xhr.status >= 200 && xhr.status < 300) {
                                                    // 成功 - 跟随重定向到我的借阅页面
                                                    window.location.href = '/loans/my';
                                                } else if (xhr.status === 302) {
                                                    // 处理重定向
                                                    const redirectUrl = xhr.getResponseHeader('Location');
                                                    if (redirectUrl) {
                                                        window.location.href = redirectUrl;
                                                    } else {
                                                        window.location.href = '/loans/my';
                                                    }
                                                } else {
                                                    // 尝试解析错误消息
                                                    let errorMsg = '借阅失败，请重试';
                                                    try {
                                                        const response = JSON.parse(xhr.responseText);
                                                        if (response.error) {
                                                            errorMsg = response.error;
                                                        }
                                                    } catch (e) {
                                                        // 如果不是JSON格式，使用默认错误消息
                                                    }
                                                    alert(errorMsg);
                                                    // 恢复按钮状态
                                                    button.disabled = false;
                                                    button.innerHTML = '<i class="fas fa-book"></i> 借阅此书';
                                                }
                                            };
                                            
                                            xhr.onerror = function() {
                                                alert('借阅请求发生网络错误，请检查网络连接');
                                                // 恢复按钮状态
                                                button.disabled = false;
                                                button.innerHTML = '<i class="fas fa-book"></i> 借阅此书';
                                            };
                                            
                                            xhr.send('days=30');
                                        });
                                    });
                                });
                            </script>
                            
                            <!-- 管理员操作 -->
                            <div class="mt-4" sec:authorize="hasRole('ADMIN')">
                                <a th:href="@{/books/admin/edit/{id}(id=${book.id})}" class="btn btn-warning me-2">
                                    <i class="fas fa-edit"></i> 编辑图书
                                </a>
                                <form class="d-inline" th:action="@{/books/admin/delete/{id}(id=${book.id})}" method="post" onsubmit="return confirm('确定要删除这本书吗？');">
                                    <button type="submit" class="btn btn-danger">
                                        <i class="fas fa-trash"></i> 删除图书
                                    </button>
                                </form>
                            </div>
                        </div>
                    </div>
                    
                    <!-- 返回按钮 -->
                    <a th:href="@{/books/list}" class="btn btn-outline-secondary">
                        <i class="fas fa-arrow-left"></i> 返回图书列表
                    </a>
                </div>
                
                <!-- 借阅状态和历史 (仅管理员可见) -->
                <div class="col-md-4" sec:authorize="hasRole('ADMIN')">
                    <div class="card">
                        <div class="card-header bg-info text-white">
                            <h5 class="card-title mb-0">借阅记录</h5>
                        </div>
                        <div class="card-body">
                            <div th:if="${#lists.isEmpty(loans)}" class="text-center py-3">
                                <p class="text-muted">暂无借阅记录</p>
                            </div>
                            <ul th:unless="${#lists.isEmpty(loans)}" class="list-group list-group-flush">
                                <li class="list-group-item" th:each="loan : ${loans}">
                                    <div class="d-flex justify-content-between align-items-center">
                                        <div>
                                            <strong th:text="${loan.user.name}">用户名</strong>
                                            <br>
                                            <small class="text-muted" th:text="'借出: ' + ${#temporals.format(loan.loanDate, 'yyyy-MM-dd')}">借出日期</small>
                                            <br th:if="${loan.returnDate}">
                                            <small class="text-muted" th:if="${loan.returnDate}" th:text="'归还: ' + ${#temporals.format(loan.returnDate, 'yyyy-MM-dd')}">归还日期</small>
                                        </div>
                                        <div>
                                            <span th:if="${loan.status.name() == 'BORROWED'}" class="badge bg-primary">借出</span>
                                            <span th:if="${loan.status.name() == 'RETURNED'}" class="badge bg-success">已还</span>
                                            <span th:if="${loan.status.name() == 'OVERDUE'}" class="badge bg-danger">逾期</span>
                                        </div>
                                    </div>
                                </li>
                            </ul>
                        </div>
                    </div>
                </div>
            </div>
        </main>
    </div>
    
    <!-- 页脚 -->
    <footer th:replace="~{fragments/layout :: footer}"></footer>
    
    <!-- 脚本 -->
    <div th:replace="~{fragments/layout :: scripts}"></div>
</body>
</html>
